package com.frxuexi.repair.view

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.KeyBean
import com.frxuexi.lib_base.entity.RepairBeanItem
import com.frxuexi.lib_base.http.Const
import com.frxuexi.lib_base.http.RequestType
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.utils.DateTimeUtils
import com.frxuexi.repair.R
import com.frxuexi.repair.RepairIntent
import com.frxuexi.repair.RepairViewModel
import com.frxuexi.repair.adapter.RepairImgAdapter
import com.frxuexi.repair.databinding.ActivityRepairEditBinding
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/repair/RepairEditActivity")
@AndroidEntryPoint
class RepairEditActivity : BaseActivity<ActivityRepairEditBinding,RepairIntent,RepairViewModel>() {
    override val binding: ActivityRepairEditBinding by lazy { ActivityRepairEditBinding.inflate(layoutInflater) }
    override val vm: RepairViewModel by viewModels<RepairViewModel>()
    val repairImgAdapter by lazy { RepairImgAdapter() }
    val imgs= mutableListOf<String>()
    var area=""

    @JvmField
    @Autowired
    var id:Int?=-1

    val areas= mutableListOf<String>()
    var status=""

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        when(it.type){
                            RequestType.SELECT_KEY->{
                                if(id!=-1){
                                    vm.sendIntent(RepairIntent.getRepairById(id!!))
                                }
                                val keyBean = it.data as KeyBean
                                areas.addAll(keyBean.filter { it.key=="parkArea" }.map { it.value })
                                val areaAdapter = ArrayAdapter(
                                    this@RepairEditActivity,
                                    android.R.layout.simple_spinner_item,
                                    areas
                                )
                                Log.i("lr",area.toString())
                                areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                                binding.repairEditLoc.adapter=areaAdapter

                               binding.repairEditLoc.onItemSelectedListener=object :OnItemSelectedListener{
                                   override fun onItemSelected(
                                       parent: AdapterView<*>?,
                                       view: View?,
                                       position: Int,
                                       id: Long
                                   ) {
                                       area=areas.get(position)
                                   }

                                   override fun onNothingSelected(parent: AdapterView<*>?) {
                                   }
                               }
                            }
                            RequestType.UPLOAD->{
                                ToastUtils.showLong("上传成功")
                                val s = it.data as String
                                val fname = s.split(":")[1]
                                imgs.add("http://10.161.9.80:2209/images/repair/${SPUtils.getInstance().getInt(Const.UID,-1)}/${fname}")
                                repairImgAdapter.addData("http://10.161.9.80:2209/images/repair/${SPUtils.getInstance().getInt(Const.UID,-1)}/${fname}")
                                repairImgAdapter.notifyDataSetChanged()
                            }
                            RequestType.ADD->{
                                ToastUtils.showLong("报修成功")
                                finish()
                            }
                            RequestType.SELECT_ITEM->{
                                val beanItem = it.data as RepairBeanItem
                                binding.repairEditName.setText(beanItem.repairName)
                                binding.repairEditPhone.setText(beanItem.contactMethod)
                                binding.repairEditLoc.setSelection(areas.indexOf(beanItem.repairLocation))
                                binding.repairEditDesc.setText(beanItem.faultDescription)
                                imgs.addAll(beanItem.faultPhotos.split(","))
                                repairImgAdapter.addData(imgs)
                                repairImgAdapter.notifyDataSetChanged()
                                status=beanItem.processingStatus
                            }

                            RequestType.UPDATE->{
                                ToastUtils.showLong("修改成功")
                                finish()
                            }

                            else -> {}
                        }

                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        ARouter.getInstance().inject(this)
        vm.sendIntent(RepairIntent.getLocs)

        binding.repairEditAdd.setOnClickListener {
            if(repairImgAdapter.data.size==4){
                ToastUtils.showLong("图片已达上限")
                return@setOnClickListener
            }
            PictureSelector.create(this,PictureSelector.SELECT_REQUEST_CODE).selectPicture()
        }

        binding.repairEditRv.apply {
            adapter=repairImgAdapter
            layoutManager=GridLayoutManager(this@RepairEditActivity,3)
        }

        repairImgAdapter.addChildClickViewIds(R.id.img_delete)
        repairImgAdapter.setOnItemChildClickListener { adapter, view, position ->
            imgs.removeAt(position)
            repairImgAdapter.data.removeAt(position)
            repairImgAdapter.notifyItemRemoved(position)
        }

        binding.repairEditName.setText(SPUtils.getInstance().getString(Const.UNAME,""))

        binding.repairCommit.setOnClickListener {
            val phone = binding.repairEditPhone.text.toString()
            val desc = binding.repairEditDesc.text.toString()
            val item = RepairBeanItem(
                phone,
                desc,
                imgs.joinToString(","),
                null,
                "WX${DateTimeUtils.getDateTimeFont()}",
                "待处理",
                area,
                binding.repairEditName.text.toString(),
                DateTimeUtils.getDateTime(System.currentTimeMillis()),
                SPUtils.getInstance().getInt(Const.UID, -1)
            )
            if(id!=-1){
                item.id=id
                item.processingStatus=status
                vm.sendIntent(RepairIntent.updateRepair(id!!,item))
            }else {
                vm.sendIntent(RepairIntent.addRepair(item))
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==PictureSelector.SELECT_REQUEST_CODE && resultCode== RESULT_OK){
            val bean = data?.extras?.getParcelable<PictureBean>(PictureSelector.PICTURE_RESULT)
            val path = bean?.path!!


            val split = path.split("/")
            val name = split.get(split.lastIndex)
            vm.sendIntent(RepairIntent.upload(name,path))
        }
    }

}